/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OficinaDialog.java
 *
 * Created on 21/10/2011, 13:26:50
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Oficina;
import br.com.seguradora.model.Telefone;
import br.com.seguradora.model.constant.Porte;
import br.com.seguradora.service.OficinaService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.StateEntityWindow;
import br.com.seguradora.view.UserError;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class OficinaDialog extends javax.swing.JDialog {

    private Oficina oficina;
    private final static String titleWindow = "Oficina";
    private StateEntityWindow stateEntity;
    
    public OficinaDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Oficina oficina) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setOficina(oficina);
        organizeWindow();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cabecalhoPanel = new br.com.seguradora.view.panel.CabecalhoPanel();
        jLabel1 = new javax.swing.JLabel();
        razaoSocialField = new javax.swing.JTextField();
        nomeErrorLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        porteCombo = new javax.swing.JComboBox();
        enderecoPanel = new br.com.seguradora.view.panel.EnderecoPanel();
        telefonesPanel = new br.com.seguradora.view.panel.TelefonesPanel();
        observacaoPanel = new br.com.seguradora.view.panel.ObservacaoPanel();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        responsavelField = new javax.swing.JTextField();
        responsavelErrorLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Razão Social:");

        nomeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel3.setText("Porte:");

        porteCombo.setModel(new DefaultComboBoxModel(Porte.values()));

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("Responsável:");

        responsavelErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(responsavelField)
                            .addComponent(razaoSocialField, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE))
                        .addGap(4, 4, 4)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(responsavelErrorLabel)
                            .addComponent(nomeErrorLabel))))
                .addContainerGap(42, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addComponent(porteCombo, 0, 162, Short.MAX_VALUE)
                .addGap(299, 299, 299))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(32, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(telefonesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap(261, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(razaoSocialField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(responsavelField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(responsavelErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(porteCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(telefonesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            OficinaService oficinaService = new OficinaService();
            Oficina oficina = getOficina();
            if (getStateEntity() == StateEntityWindow.NEW) {
                oficinaService.inserir(oficina);
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                oficinaService.atualizar(oficina);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
}//GEN-LAST:event_confirmarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
}//GEN-LAST:event_cancelarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                OficinaDialog dialog = new OficinaDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.seguradora.view.panel.CabecalhoPanel cabecalhoPanel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private br.com.seguradora.view.panel.EnderecoPanel enderecoPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel nomeErrorLabel;
    private br.com.seguradora.view.panel.ObservacaoPanel observacaoPanel;
    private javax.swing.JComboBox porteCombo;
    private javax.swing.JTextField razaoSocialField;
    private javax.swing.JLabel responsavelErrorLabel;
    private javax.swing.JTextField responsavelField;
    private br.com.seguradora.view.panel.TelefonesPanel telefonesPanel;
    // End of variables declaration//GEN-END:variables

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            cabecalhoPanel.setBloqueado(false);
            cabecalhoPanel.isEnabledComponentBloqueado(false);
            telefonesPanel.setTelefonesList(new ArrayList<Telefone>());
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (razaoSocialField.getText().isEmpty()) {
            errorsList.addError(new UserError(nomeErrorLabel, "A razão social não foi informada."));
        }
        if(responsavelField.getText().isEmpty()) {
            errorsList.addError(new UserError(responsavelErrorLabel, "O nome do responsável não foi informado."));
        }
        if(enderecoPanel.getEndereco() == null) {
            errorsList.addError(new UserError(enderecoPanel.getLogradouroErrorLabel(), "O endereço da oficina não foi informado."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }

    private void isShowErrorsLabel(boolean show) {
        nomeErrorLabel.setVisible(show);
        responsavelErrorLabel.setVisible(show);
        enderecoPanel.getLogradouroErrorLabel().setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
    
    private Oficina getOficina() {
        if(oficina == null) {
            this.oficina = new Oficina();
        }
        oficina.setBloqueado(cabecalhoPanel.isBloqueado());
        oficina.setRazaoSocial(razaoSocialField.getText().toUpperCase());
        oficina.setResponsavel(responsavelField.getText().toUpperCase());
        oficina.setPorte((Porte) porteCombo.getSelectedItem());
        oficina.setEndereco(enderecoPanel.getEndereco());
        oficina.setTelefonesList(telefonesPanel.getTelefonesList());
        oficina.setObservacao(observacaoPanel.getObservacao());
        return oficina;
    }
    
    private void setOficina(Oficina oficina) {
        if(oficina == null) {
            return;
        }
        this.oficina = oficina;
        cabecalhoPanel.setCodigo(oficina.getId());
        cabecalhoPanel.setBloqueado(oficina.isBloqueado());
        razaoSocialField.setText(oficina.getRazaoSocial());
        responsavelField.setText(oficina.getResponsavel());
        porteCombo.setSelectedItem(oficina.getPorte());
        enderecoPanel.setEndereco(oficina.getEndereco());
        telefonesPanel.setTelefonesList(oficina.getTelefonesList());
        observacaoPanel.setObservacao(oficina.getObservacao());
    }
    
    public Oficina objetoOficina() {
        return oficina;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
